<?php

namespace MoChat\App\Client\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use MoChat\App\Client\Model\Client;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use TheSeer\Tokenizer\Exception;
use Hyperf\Command\Annotation\Command;

/**
 * @Command
 */
class ClientImportCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('importClient');
    }

    public function configure()
    {
        parent::configure();
        $this->addOption('clear', 'C', InputArgument::OPTIONAL, '清除redis', 0);
        $this->setDescription('客户导入');
    }

    public function handle()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        $clear = $this->input->getOption('clear');
        if ($clear) {
            $redis->del('ClientImportCommand_key');
        }
        $bool = $redis->get('ClientImportCommand_key');
        if ($bool) {
            $this->line('上一个销售任务同步脚本程序正在执行中', 'info');
        } else {
            $redis->set('ClientImportCommand_key', true, 300);
            ini_set("max_execution_time", "0");
            ini_set("memory_limit", "1G");
            // 有Xls和Xlsx格式两种
            $tasks = Db::table('tasks')->where('status', 0)->first();
            $error = [];
            if (!empty($tasks)) {
                $objReader = IOFactory::createReader('Xlsx');
                $filename = $tasks->data;
                $objReader->setReadDataOnly(TRUE);
                $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
                $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
                $highestRow = $sheet->getHighestRow();       // 取得总行数
                $uniqueIds = Db::table('client')->pluck('unique_id')->toArray();
                $enterpriseNames = Db::table('client')->pluck('enterprise_name')->toArray();
                $district = Db::table('district')->pluck('id', 'name')->toArray();
                $date = date('Y-m-d H:i:s');
                for ($j = 2; $j <= $highestRow; $j++) {
                    $type = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                    $uniqueId = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                    $enterpriseName = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                    if (!in_array($uniqueId, $uniqueIds) && !in_array($enterpriseName, $enterpriseNames)) {
                        $province = str_replace('省', '', $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue());
                        $city = str_replace('市', '', $objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue());
                        $d = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue();
                        $data = [
                            'unique_id' => $uniqueId,
                            'enterprise_name' => $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue(),
                            'mobile' => $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue(),
                            'b2b_user_type' => (int)$type,
                            'address' => $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue(),
                            'b2b_register_time' => date('Y-m-d H:i:s', Date::excelToTimestamp($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue(), 'PRC')),
                            'b2b_manager_name' => $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue(),
                            'b2b_salesman_name' => $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue(),
                            'province' => $district[$province] ?? 0,
                            'city' => $district[$city] ?? 0,
                            'district' => $district[$d] ?? 0,
                            'created_at' => $date
                        ];
                        $uniqueIds[] = $uniqueId;
                        $enterpriseNames[] = $enterpriseName;
                        try {
                            Client::insert($data);
                        } catch (\Throwable $throwable) {
                            $error[] = $data;
                        }
                    }
                }
                Db::table('tasks')->where('id', $tasks->id)->update([
                    'status' => 1,
                    'remark' => json_encode($error, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            }

            $redis->del('ClientImportCommand_key');
            $this->line('客户导入完成', 'info');
        }
    }
}
